package view;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineEvent.Type;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 * The static sound class provide sound asset to Tanks. Unfortunately, Java can
 * only play Mono audio files so if you are wondering why your sound is not
 * being played convert the audio file using audacity to mono.
 * 
 * @author Gopal Adhikari 
 * 
 */

public class Sound {

	/**
	 * The Sound class for Tanks. Call this static method to play a desired
	 * sound used in the game. *
	 * 
	 * @param soundID
	 *            Each sound that is played by this method is loaded from the
	 *            running directory. The soundID parameter is a unique
	 *            identifier of such sound.
	 * 
	 * @throws InterruptedException
	 * @throws LineUnavailableException
	 * @throws UnsupportedAudioFileException
	 * @throws IOException
	 */

	public static void main(String[] args) throws IOException,
			UnsupportedAudioFileException, LineUnavailableException,
			InterruptedException {
		Sound.play(GameSound.FIRE_CANON);
	}

	public static void play(GameSound soundID) throws IOException,
			UnsupportedAudioFileException, LineUnavailableException,
			InterruptedException {

		switch (soundID) {
		case MAIN_MENU:
			playerHelper("sounds/boom.wav");
			break;
		case FIRE_CANON:
			playerHelper("sounds/boom.wav");
			break;
		case BOOM:
			playerHelper("sounds/boom.wav");
			break;
		case SWOOSH:
			playerHelper("sounds/boom.wav");
		default:
			break;
		}
	}

	private static void playerHelper(String fileName) throws IOException,
			UnsupportedAudioFileException, LineUnavailableException,
			InterruptedException {
		class AudioListener implements LineListener {
			private boolean isDonePlaying = false;

			@Override
			public synchronized void update(LineEvent evt) {
				Type evtType = evt.getType();
				if (evtType == Type.STOP || evtType == Type.CLOSE) {
					isDonePlaying = true;
					notifyAll();
				}
			}

			public synchronized void waitUntilDone()
					throws InterruptedException {
				while (!isDonePlaying) {
					wait();
				}
			}
		}

		AudioListener listener = new AudioListener();
		AudioInputStream audioInput = AudioSystem.getAudioInputStream(new File(
				fileName));
		try {
			Clip audioClip = AudioSystem.getClip();
			audioClip.addLineListener(listener);
			audioClip.open(audioInput);
			try {
				audioClip.start();
				listener.waitUntilDone();
			} finally {
				audioClip.close();
			}
		} finally {
			audioInput.close();
		}
	}
}
